package com.wh.wisdomsite.xbox.common.reponse;

import com.wh.wisdomsite.xbox.common.error.MainError;
import com.wh.wisdomsite.xbox.common.error.SubError;
import com.wh.wisdomsite.xbox.common.error.SubErrorType;
import com.wh.wisdomsite.xbox.common.error.SubErrors;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Locale;


/***
 * 功能说明：服务不可用响应类
 * @Package com.wh.wisdomsite.xbox.common.reponse
 * @author 谢泽鹏
 * @date 2016年11月07日 下午15:10
 * @Copyright 个人版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2016
 * @version V1.0
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "error")
public class ServiceUnavailableErrorResponse extends ErrorResponse {

    private static final String ISP = "isp.";

    private static final String SERVICE_UNAVAILABLE = "-service-unavailable";

    /**
     * 构造函数
     */
    public ServiceUnavailableErrorResponse() {

    }

    public ServiceUnavailableErrorResponse(String method, Locale locale) {
        MainError mainError = SubErrors.getMainError(SubErrorType.ISP_SERVICE_UNAVAILABLE, locale);
        String subErrorCode = ISP + transform(method) + SERVICE_UNAVAILABLE;
        SubError subError = SubErrors.getSubError(subErrorCode, SubErrorType.ISP_SERVICE_UNAVAILABLE.value(),
                locale, method, "NONE", "NONE");

        getSubErrors().add(subError);
        setMainError(mainError);
    }

    public ServiceUnavailableErrorResponse(String method, Locale locale, Throwable throwable) {
        MainError mainError = SubErrors.getMainError(SubErrorType.ISP_SERVICE_UNAVAILABLE, locale);
        String subErrorCode = ISP + transform(method) + SERVICE_UNAVAILABLE;
        Throwable srcThrowable = throwable;
        if (throwable.getCause() != null) {
            srcThrowable = throwable.getCause();
        }

        SubError subError = SubErrors.getSubError(subErrorCode, SubErrorType.ISP_SERVICE_UNAVAILABLE.value(),
                locale, method, srcThrowable.getClass().getName(), getThrowableInfo(throwable));

        getSubErrors().add(subError);
        setMainError(mainError);

    }


    public String getThrowableInfo(Throwable throwable) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024);
        PrintStream printStream = new PrintStream(outputStream);
        throwable.printStackTrace(printStream);
        return outputStream.toString();
    }


}
